const path = require('path')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const babel = require('@babel/core')
const less = require('less')

module.exports = {
    mode: 'development',
    watch: true,
    entry: './src/app.js',
    output: {
        path: path.join(__dirname, 'dist')
    },
    plugins: [
        new CopyWebpackPlugin({
            patterns: [
                {
                    from: '**/*.js',
                    to: './',
                    transform(content, path) {
                        const newCode = babel.transform(content, {
                            babelrc: true,
                            "presets": ["@babel/env"]
                        }).code
                        return Promise.resolve(newCode.toString())
                    },
                    context: './src',
                    globOptions: {
                        ignore: ['**/*.test.js', '**/*.spec.js'],
                    }
                },
                {from: '**/*.wxml', to: './', context: './src'},
                {from: '**/*.json', to: './', context: './src'},
                // {from: '**/*.jpg', to: './', context: './src'},
                // {from: '**/*.png', to: './', context: './src'},
                {
                    from: '**/*.less',
                    to({context, absoluteFilename}) {
                        // 这里怎么获取到output的值？硬编码感觉不太好？
                        return absoluteFilename.replace('/src/', '/dist/')
                                .replace('.less', '.wxss')
                    },
                    context: './src',
                    transform(content, path) {
                        return less.render(content.toString())
                            .then(function (output) {
                                return output.css
                            })
                    },
                },
                {from: '**/*.wxss', to: './', context: './src'},
            ]
        })
    ]
}
